package com.java.util;

import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class TimeTest {

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.parse("2025-04-10", formatter);

//        LocalDate today = LocalDate.now(); // 当前日期

        // 当前月的第一天
        LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("当前月第一天: " + firstDayOfMonth);

        // 当前月的最后一天
        // System.out.println(today.withDayOfMonth(1).toString());
        // 当前月的最后一天，这个方法不太好，如果本月30天，直接设置为31会出错
        // System.out.println(today.withDayOfMonth(31).toString());

        // 当前月的最后一天
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("当前月最后一天: " + lastDayOfMonth);


        YearMonth currentYearMonth = YearMonth.now(); // 当前年月

        LocalDate firstDay = currentYearMonth.atDay(1); // 第一天
        LocalDate lastDay = currentYearMonth.atEndOfMonth(); // 最后一天

        System.out.println("当前月第一天: " + firstDay);
        System.out.println("当前月最后一天: " + lastDay);

        LocalDate endDay = LocalDate.parse("2025-04-10", formatter);

        System.out.println("当前季度第一天: " + getFirstDayOfQuarter(today));
        System.out.println("当前季度最后一天: " + getLastDayOfQuarter(endDay));
    }


    /**
     * 获取当前季度的第一天
     */
    public static LocalDate getFirstDayOfQuarter(LocalDate date) {
        Month firstMonthOfQuarter = date.getMonth().firstMonthOfQuarter();
        return LocalDate.of(date.getYear(), firstMonthOfQuarter, 1);
    }

    /**
     * 获取当前季度的最后一天
     */
    public static LocalDate getLastDayOfQuarter(LocalDate date) {
        Month firstMonthOfQuarter = date.getMonth().firstMonthOfQuarter();
        Month lastMonthOfQuarter = firstMonthOfQuarter.plus(2);
        return LocalDate.of(date.getYear(), lastMonthOfQuarter, 1).with(TemporalAdjusters.lastDayOfMonth());
    }
}
